﻿<template>
  <a-drawer
    :title="title"
    width="90%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @close="
      () => {
        this.visible = false
      }
    "
    :body-style="{ paddingBottom: '5%' }"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="entity" :rules="rules" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="生产日期" prop="InDate">
              <a-date-picker
                v-model="entity.InDate"
                format="YYYY-MM-DD"
                autocomplete="off"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="部门" prop="Department" :labelCol="{ style: 'width: 20%;float:left;' }">
              <a-tree-select
                v-model="entity.Department"
                allowClear
                :treeData="DepartmentIdTreeData"
                placeholder="请选择部门"
                treeDefaultExpandAll
              ></a-tree-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="操作人" prop="Creator">
              <a-input v-model="Creator" autocomplete="off" placeholder="操作人" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="">
              <a-button @click="addOtherChange" type="primary" :disabled="disabled" style="margin-bottom: 10px;margin-left: 80px;">+&nbsp;&nbsp;添加</a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="30" v-for="(item, index) in jsonList" :key="item.key" class="bordered-row">
          <a-row>
            <a-col :span="23">
              <a-row >
                <a-row>
                  <a-col> <span style="font-weight: bold;margin-left: 10px;">物料信息</span></a-col>
                </a-row>
                <a-row>
                  <a-col :span="4">
                    <a-form-model-item label="编号" prop="InvCode">
                      <a-row>
                        <a-col :span="19">
                          <a-input v-model="item.InvCode" disabled></a-input>
                        </a-col>
                        <a-col :span="5"><a-button icon="search" type="primary" style="width: 100%;margin-top: 4px;" @click="openClient(index)"></a-button></a-col>
                      </a-row>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="4">
                    <a-form-model-item label="品名" prop="InvName">
                      <a-input v-model="item.InvName" autocomplete="off" placeholder="品名" disabled/>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="5">
                    <a-form-model-item label="规格型号" prop="InvStd">
                      <a-input v-model="item.InvStd" autocomplete="off" placeholder="规格型号"/>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="5">
                    <a-form-model-item label="生产批号" prop="ProBatch">
                      <a-input v-model="item.ProBatch" autocomplete="off" placeholder="生产批号" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="5">
                    <a-form-model-item label="平均价格" prop="AvgPrice">
                      <a-input v-model="item.AvgPrice" autocomplete="off" placeholder="平均价格" disabled/>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row >
                  <a-col :span="2"> <span style="font-weight: bold;margin-left: 10px;">出库信息</span></a-col>
                  <a-col :span="2"> <a-button type="primary" :disabled="disabled" style="margin-bottom: 10px;" @click="openRdRecord(index)">选择出库</a-button></a-col>
                </a-row>
                <a-row>
                  <a-table
                    id="tables"
                    ref="tableExport"
                    :scroll="{ y: tableHight }"
                    :columns="columns"
                    :rowKey="(row, dindex) => row.Id"
                    :dataSource="item.cm_Productionitems"
                    :loading="loading"
                    :pagination="false"
                    :bordered="true"
                    size="small"
                  >
                    <span slot="OutDate" slot-scope="OutDate">{{ timeFormat(OutDate,'YYYY-MM-DD') }}</span>
                    <template slot="InQty" slot-scope="text, record, dindex">
                      <a-input style="width:100%" v-model="record.InQty" @change="tableChange($event,'InQty',dindex,index)" ></a-input>
                    </template>
                    <template slot="ProcessingCosts" slot-scope="text, record, dindex">
                      <a-input style="width:100%" v-model="record.ProcessingCosts" @change="tableChange($event,'ProcessingCosts',dindex,index)" ></a-input>
                    </template>
                    <span slot="Loss" slot-scope="Loss">{{ (Loss * 100).toFixed(0) + '%' }}</span>
                    <!--              <template slot="Loss" slot-scope="text, record, dindex">-->
                    <!--                <a-input style="width:100%" v-model="record.Loss" ></a-input>-->
                    <!--              </template>-->
                    <!--              <template slot="InPrice" slot-scope="text, record, index">-->
                    <!--                <a-input style="width:100%" v-model="record.InPrice" ></a-input>-->
                    <!--              </template>-->
                    <template slot="action" slot-scope="text, record, dindex">
                      <a
                        :disabled="disabled"
                        @click="handleDelete([record.Id], index, dindex)"
                      >删除</a>
                    </template>
                  </a-table>
                </a-row>
              </a-row>
            </a-col>
            <a-col :span="1">
              <a-row>
                <a-col style="height: 120px">
                  <span></span>
                </a-col>
                <a-col style="margin-left: 16px;">
                  <a-button type="danger" class="delbut" @click="deleteItem(item,[item.Id], index)" :disabled="disabled">
                    <a-icon type="delete" />
                  </a-button>
                </a-col>
              </a-row>
            </a-col>
          </a-row>
        </a-row>
      </a-form-model>
    </a-spin>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <a-button
        :style="{ marginRight: '8px' }"
        @click="
          () => {
            this.visible = false
          }
        "
      >取消</a-button
      >

      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </div>
    <select-inventory ref="SelectInventory" :parentObj="this" @inputInv="inputInv"></select-inventory>
    <select-rd-record-select ref="SelectRdRecordSelect" :parentObj="this" @inputRd="inputRd"></select-rd-record-select>
  </a-drawer>
</template>

<script>
import SelectInventory from './../../MaterialManagement/AA_Inventory/List'
import SelectRdRecordSelect from './MaterialRdRecordSelect'
import moment from 'moment'
const columns = [
  { title: '出库日期', dataIndex: 'OutDate', align: 'center', width: '5%', scopedSlots: { customRender: 'OutDate' } },
  { title: '原料批号', dataIndex: 'RawBatch', align: 'center', width: '8%' },
  { title: '供应商', dataIndex: 'Supplier', align: 'left', width: '12%' },
  { title: '原材料数量', dataIndex: 'OutQty', align: 'left', width: '5%' },
  { title: '原材料单价', dataIndex: 'OutPrice', align: 'left', width: '5%' },
  { title: '成品数量', dataIndex: 'InQty', align: 'left', width: '5%', scopedSlots: { customRender: 'InQty' } },
  { title: '加工成本', dataIndex: 'ProcessingCosts', align: 'left', width: '5%', scopedSlots: { customRender: 'ProcessingCosts' } },
  { title: '损耗百分比', dataIndex: 'Loss', align: 'left', width: '5%', scopedSlots: { customRender: 'Loss' } },
  { title: '成本单价', dataIndex: 'InPrice', align: 'left', width: '5%', scopedSlots: { customRender: 'InPrice' } },
  { title: '操作', dataIndex: 'action', align: 'left', width: '5%', scopedSlots: { customRender: 'action' } }
]
function formatNumber (value) {
  return Number(value).toFixed(2)
}
export default {
  components: {
    SelectInventory,
    SelectRdRecordSelect
  },
  props: {
    parentObj: Object,
    afterSubmit: {
      type: Function,
      default: null
    }
  },
  data () {
    return {
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      tableHight: 570, // 表格高度
      columns,
      visible: false,
      loading: false,
      entity: {},
      jsonList: [], // 备注列表
      DepartmentIdTreeData: [],
      disabled: false,
      confirmLoading: false,
      Creator: '',
      DetaiData: [],
      title: '',
      listindex: 0,
      rules: {
        InDate: [{ required: true, message: '必填' }]
      }
    }
  },
  computed: {
    DetaiDataComputed () {
      return this.DetaiData.map(item => {
        // 损耗百分比 （原数量-成品数量）/原数量
        this.$set(item, 'Loss', this.$number.minus(this.$number.minus(Number(item.OutQty), Number(item.InQty)), Number(item.OutQty)))
        // 成本单价 （（原价*原数量）/成品数量）+ 加工成本
        this.$set(item, 'InPrice', this.$number.add(this.$number.minus((this.$number.mut(Number(item.OutPrice), Number(item.OutQty))), Number(item.InQty)), Number(item.ProcessingCosts)))

        return {
          ...item

        }
      })
    }
  },
  methods: {
    init () {
      this.visible = true
      this.entity = {}
      this.$set(this.entity, 'InDate', moment().format('YYYY-MM-DD'))
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    openForm (id, title) {
      this.init()
      this.jsonList = []
      this.title = title
      if (localStorage.getItem('UserInfo')) {
        this.UserInfo = JSON.parse(localStorage.getItem('UserInfo'))
      }
      this.$http.post('/Base_Manage/Base_Department/GetTreeDataList', {}).then(resJson => {
        if (resJson.Success) {
          this.DepartmentIdTreeData = resJson.Data
        }
      })
      this.Creator = this.UserInfo.RealName
      if (id) {
        this.loading = true
        this.$http.post('/CostManagement/cm_productionmain/GetTheData', { id: id }).then(resJson => {
          this.loading = false
          console.log(resJson.Data, 666)
          this.entity = resJson.Data
          this.Creator = resJson.Data.Creator
          this.jsonList = this.entity.cm_Productionsubs
          if (this.jsonList === null) {
            this.jsonList = []
          }
          this.jsonList.forEach(item => {
            if (item.cm_Productionitems === null) {
              item.cm_Productionitems = []
            }
          })
        })
      }
    },
    openClient (index) {
      this.listindex = index
      this.$refs.SelectInventory.openForm('选择物料')
    },
    openRdRecord (index) {
      this.listindex = index
      if (!this.jsonList[this.listindex].InvCode) {
        alert('请先选择物料！')
        return
      }
      this.$refs.SelectRdRecordSelect.openForm('选择出库信息', this.jsonList[this.listindex].InvCode)
    },
    handleSubmit () {
      const ddata = {
        ...this.entity,
        cm_Productionsubs: [...this.jsonList]
      }
      console.log(ddata)
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        this.confirmLoading = true
        this.$http.post('/CostManagement/cm_productionmain/SaveData', ddata).then(resJson => {
          this.confirmLoading = false
          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.visible = false
            // this.afterSubmit()
            this.parentObj.getDataList()
          } else {
            this.$message.error(resJson.Msg)
          }
        })
      })
    },
    // 增加项
    addOtherChange () {
      // const uuid = require('uuid')
      // const uniqueId = uuid.v4()
      this.$set(this.jsonList, this.jsonList.length, {
        cm_Productionitems: [],
        // uid: uniqueId,
        InvCode: '',
        InvName: '',
        InvStd: '',
        AvgPrice: '',
        InvId: '',
        ProBatch: ''
      })
      console.log('获取jsonlist', this.jsonList)
    },
    deleteItem (item, ids, index) {
      console.log(typeof ids[0])
      if (typeof ids[0] === "undefined") {
        this.jsonList.splice(index, 1)
        return
      }
      const thisObj = this
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          thisObj.submitDelete(ids, resolve, index)
        }).catch(() => console.log('Oops errors!')),
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    submitDelete (ids, resolve, index) {
      this.$http.post('/CostManagement/cm_productionsub/DeleteData', ids).then(resJson => {
        resolve()

        if (resJson.Success) {
          this.$message.success('操作成功!')
          this.jsonList.splice(index, 1)

          this.getDataList()
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    },
    inputInv (arr) {
      const obj = arr[0]
      console.log(arr)
      if (obj) {
        this.$set(this.jsonList[this.listindex], 'InvCode', obj.code)
        this.$set(this.jsonList[this.listindex], 'InvName', obj.name)
        this.$set(this.jsonList[this.listindex], 'InvStd', obj.specification)
        this.$set(this.jsonList[this.listindex], 'InvId', obj.Id)
      }
    },
    inputRd (arr) {
      this.loading = true
      const nArr = [...arr]
      console.log(arr)
      nArr.forEach(item => {
        this.$set(item, 'OutDate', item.OutDate)
        this.$set(item, 'RawBatch', item.Batch)
        this.$set(item, 'Supplier', item.Superlier)
        this.$set(item, 'OutQty', item.Qty)
        this.$set(item, 'OutPrice', item.Price)
        this.$set(item, 'Loss', 0)
        this.$set(item, 'InPrice', 0)
        this.$set(item, 'ProcessingCosts', 0)
        delete item.Id
        delete item.Qty
        delete item.Price
        delete item.Batch
      })
      this.jsonList[this.listindex].cm_Productionitems = [...nArr, ...this.jsonList[this.listindex].cm_Productionitems]
      console.log(this.jsonList)
      this.loading = false
    },
    tableChange (val, key, index, rowindex) {
      this.loading = true
      const obj = this.jsonList[rowindex].cm_Productionitems[index]
      // this.$set(this.jsonList[index], key, val)
      if (key === 'InQty') {
        console.log(this.$number.dev(this.$number.minus(Number(obj.OutQty), Number(obj.InQty)), Number(obj.OutQty)))
        // 损耗百分比 （原数量-成品数量）/原数量
        this.$set(this.jsonList[rowindex].cm_Productionitems[index], 'Loss', formatNumber(this.$number.dev(this.$number.minus(Number(obj.OutQty), Number(obj.InQty)), Number(obj.OutQty))))
        // 成本单价 （（原价*原数量）/成品数量）+ 加工成本
        this.$set(this.jsonList[rowindex].cm_Productionitems[index], 'InPrice', formatNumber(this.$number.add(this.$number.dev((this.$number.mut(Number(obj.OutPrice), Number(obj.OutQty))), Number(obj.InQty)), Number(obj.ProcessingCosts))))
        console.log(this.jsonList[rowindex])
        console.log(this.jsonList)
      }
      console.log(key)
      if (key === 'ProcessingCosts') {
        console.log(rowindex, index)
        console.log(this.jsonList)
        console.log(this.jsonList[rowindex].cm_Productionitems[index])
        console.log(formatNumber(this.$number.add(this.$number.dev((this.$number.mut(Number(obj.OutPrice), Number(obj.OutQty))), Number(obj.InQty)), Number(obj.ProcessingCosts))))
        // 成本单价 （（原价*原数量）/成品数量）+ 加工成本
        this.$set(this.jsonList[rowindex].cm_Productionitems[index], 'InPrice', formatNumber(this.$number.add(this.$number.dev((this.$number.mut(Number(obj.OutPrice), Number(obj.OutQty))), Number(obj.InQty)), Number(obj.ProcessingCosts))))
      }
      let totalamount = Number(0)
      let totalQty = Number(0)
      this.jsonList[rowindex].cm_Productionitems.forEach(item => {
        totalamount += this.$number.mut(Number(item.InPrice), Number(item.InQty))
        totalQty += Number(item.InQty)
      })
      console.log(totalamount)
      console.log(totalQty)
      this.jsonList[rowindex].AvgPrice = formatNumber(this.$number.dev(Number(totalamount), Number(totalQty)))
      this.loading = false
    },
    handleDelete (ids, index, dindex) {
      console.log(typeof ids[0])
      if (typeof ids[0] === "undefined") {
        this.jsonList[index].cm_Productionitems.splice(dindex, 1)
        return
      }
      const thisObj = this
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          thisObj.submitItemDelete(ids, resolve, dindex, index)
        }).catch(() => console.log('Oops errors!')),
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    submitItemDelete (ids, resolve, dindex, index) {
      this.$http.post('/CostManagement/cm_productionitem/DeleteData', ids).then(resJson => {
        resolve()

        if (resJson.Success) {
          this.$message.success('操作成功!')
          this.jsonList[index].cm_Productionitems.splice(dindex, 1)

          this.getDataList()
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    },
    // 非空校验
    validEmpty (index, name, tips) {
      return (rule, value, callback) => {
        const data = this.DetaiData[index][name]
        if (!data) {
          this.$message.warning('列表第' + (index + 1) + '行：' + tips)
          callback(tips || '必填')
        } else {
          callback()
        }
      }
    }
  }
}
</script>
<style scoped>

.bordered-row {
  border: 1px solid #d9d9d9; /* 您可以根据需要更改边框颜色和宽度 */
  border-radius: 4px; /* 可选：为边框添加圆角 */
  padding: 10px; /* 可选：添加内边距 */
}
</style>
